from flask import Blueprint, request, jsonify
from werkzeug.exceptions import BadRequest
from app import db
from app.comments.models import Comment
from app.comments.schemas import comment_schema, comments_schema
from app.recipes.models import Recipe

# 创建评论模块的蓝图
comments_bp = Blueprint('comments', __name__)

@comments_bp.route('/', methods=['GET'])
def get_comments():
    """
    获取所有评论列表
    ---
    响应：评论列表
    """
    comments = Comment.query.all()
    return jsonify(comments_schema.dump(comments))

@comments_bp.route('/<int:comment_id>', methods=['GET'])
def get_comment(comment_id):
    """
    获取单个评论的详细信息
    ---
    参数：comment_id - 评论ID
    响应：评论详细信息
    """
    comment = Comment.query.get_or_404(comment_id)
    return jsonify(comment_schema.dump(comment))

@comments_bp.route('/', methods=['POST'])
def create_comment():
    """
    创建新评论
    ---
    请求体：评论信息
    响应：创建成功的评论信息
    """
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 验证必填字段
    required_fields = ['recipe_id', 'user_id', 'content']
    for field in required_fields:
        if field not in data:
            raise BadRequest(f'Missing required field: {field}')
    
    # 检查食谱是否存在
    recipe = Recipe.query.get(data['recipe_id'])
    if not recipe:
        raise BadRequest(f'Recipe not found: {data["recipe_id"]}')
    
    # 创建评论对象
    comment = Comment(
        recipe_id=data['recipe_id'],
        user_id=data['user_id'],
        content=data['content'],
        rating=data.get('rating')
    )
    
    db.session.add(comment)
    db.session.commit()
    
    return jsonify(comment_schema.dump(comment)), 201

@comments_bp.route('/<int:comment_id>', methods=['PUT'])
def update_comment(comment_id):
    """
    更新评论信息
    ---
    参数：comment_id - 评论ID
    请求体：更新的评论信息
    响应：更新后的评论信息
    """
    comment = Comment.query.get_or_404(comment_id)
    data = request.get_json()
    
    if not data:
        raise BadRequest('No input data provided')
    
    # 更新字段
    if 'content' in data: comment.content = data['content']
    if 'rating' in data: comment.rating = data['rating']
    
    db.session.commit()
    
    return jsonify(comment_schema.dump(comment))

@comments_bp.route('/<int:comment_id>', methods=['DELETE'])
def delete_comment(comment_id):
    """
    删除评论
    ---
    参数：comment_id - 评论ID
    响应：成功删除的消息
    """
    comment = Comment.query.get_or_404(comment_id)
    
    db.session.delete(comment)
    db.session.commit()
    
    return jsonify({'message': 'Comment deleted successfully'})

@comments_bp.route('/recipe/<int:recipe_id>', methods=['GET'])
def get_comments_by_recipe(recipe_id):
    """
    获取指定食谱的所有评论
    ---
    参数：recipe_id - 食谱ID
    响应：评论列表
    """
    recipe = Recipe.query.get_or_404(recipe_id)
    comments = Comment.query.filter_by(recipe_id=recipe_id).order_by(Comment.created_at.desc()).all()
    return jsonify(comments_schema.dump(comments))

@comments_bp.route('/user/<int:user_id>', methods=['GET'])
def get_comments_by_user(user_id):
    """
    获取指定用户的所有评论
    ---
    参数：user_id - 用户ID
    响应：评论列表
    """
    comments = Comment.query.filter_by(user_id=user_id).order_by(Comment.created_at.desc()).all()
    return jsonify(comments_schema.dump(comments))

@comments_bp.route('/recipe/<int:recipe_id>/average-rating', methods=['GET'])
def get_recipe_average_rating(recipe_id):
    """
    获取指定食谱的平均评分
    ---
    参数：recipe_id - 食谱ID
    响应：平均评分
    """
    recipe = Recipe.query.get_or_404(recipe_id)
    comments = Comment.query.filter_by(recipe_id=recipe_id, rating__isnotnull=True).all()
    
    if not comments:
        return jsonify({'average_rating': 0})
    
    total_rating = sum(comment.rating for comment in comments)
    average_rating = total_rating / len(comments)
    
    return jsonify({'average_rating': round(average_rating, 1)})